<?php

namespace App\Models;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Services\OrdersPayService;
use App\Models\Admin\UserModel;

class MoneyBilModel extends Model {

    protected $table = 'moneybill';

    /**
     * 系统账户id
     */
    const system_uid = 1;
    const PlayType_system = 0;
    const PlayType_zhifubao = 1;
    
    
    const type_chongzhi = 1;
    const type_zhuanru = 2;
    const type_tixian = 3;
    const type_zhuanchu = 4;
    const status_null = 0;
    const status_fail = 1;
    const status_Success = 2;

    public static function getType($key = null) {
        $all = [
            self::type_chongzhi => '充值',
            self::type_zhuanru => '转入',
            self::type_tixian => '提现',
            self::type_zhuanchu => '转出',
        ];
        if ($key === null) {
            return $all;
        }
        return isset($all[$key]) ? $all[$key] : null;
    }

    /**
     * 显示给用户的审核时间
     */
    const shenheTimeMsg = '预计需要2个工作日';

    public static function getPlayTepe($key = null) {
        $all = [
            self::PlayType_zhifubao => '支付宝'
        ];
        if ($key === null) {
            return $all;
        }
        return isset($all[$key]) ? $all[$key] : null;
    }

    public static function getstatus($key = null) {
        $all = [
            self::status_null => '待审核',
            self::status_fail => '失败',
            self::status_Success => '成功',
        ];
        if ($key === null) {
            return $all;
        }
        return isset($all[$key]) ? $all[$key] : null;
    }

    public function attributeLabels() {
        return [
            'id' => 'id',
            'uid' => '用户id',
            'money' => '数额',
            'type' => '类型',
            'out_trade_no' => '内部订单', //
            'out_trade_no_play' => '支付接口订单',
            'status' => '状态 ', ///是否提现成功,或者充值成功
            'ip' => 'ip',
            'ua' => 'ua',
            'notes' => '备注',
            'msg' => '信息',
            'admin' => '审核管理员的id',
            'examine_time' => '审核时间',
            'play_type' => '支付类型',
            'tixian_xingming' => '姓名',
            'tixian_zhanghu' => '提现账户',
        ];
    }
    /**
     *表示外部充值
     */
    const DEL_cz = 'y';
    /**
     * 表示内部转账
    */
    const DEL_system = 's';
    /**
     * 表示提现
    */
    const DEL_Tixian='t';

    /**
     * 生成支付订单
     */
    public static function GenNo() {
        return self::DEL_cz . date('Ymdhms') . mt_rand(1000, 9999);
    }
    /**
     * 生成内部转账订单
     */
    public static function GensystemNo() {
        return self::DEL_system . date('Ymdhms') . mt_rand(1000, 9999);
    }

    /**
     * 提现订单
    */
    public static function GenTixianNo(){
        return self::DEL_Tixian . date('Ymdhms') . mt_rand(1000, 9999);
    }



    /**
     * 创建充值一个订单,
     */
    public static function GenChongzhiOrder($play_type, $money) {
        $out_trade_no = self::GenNo();
        $uid = OA::$user->getId();
        if (!$uid) {
            OA::Json(OA::Guest, '登录状态失效');
        }
        $orderPayService = new OrdersPayService();
        $result = $orderPayService->createaAipayTrade('m', 'directpay', [
            'state' => '附加信息',
            'out_trade_no' => $out_trade_no ?? '', //支付宝交易号
            'subject' => "为ID:" . $uid . "用户充值",
            'money' => $money, //交易费用
            'body' => '平台现金充值,用户id:' . $uid, //费用描述
            'notifyUrl' => route('pay.alipay.notify'),
            'returnUrl' => route('h5_pay.alipay.success')
        ]);
        //   var_dump(route('h5_pay.alipay.notify'),route('h5_pay.alipay.success'));exit;
        if ($result === false) {
            OA::Json(1, '系统错误,请重试');
        }
        $new = new self;
        $new->uid = $uid;
        $new->time = time();
        $new->money = $money;
        $new->type = self::type_chongzhi;
        $new->out_trade_no = $out_trade_no;
        $new->out_trade_no_play = '';
        $new->status = self::status_null;
        $new->ip = Fun::Ip();
        $new->ua = Fun::UA();
        $new->notes = '';
        $new->msg = '';
        $new->admin = 0;
        $new->examine_time = 0;
        $new->play_type = $play_type;
        if ($new->save()) {
            return $result;
        } else {
            return null;
        }
    }

    /**
     * 生成提现订单
     */
    public static function GenTixian($tixianmoney, $xingming, $zhifubao) {
        $uid = OA::$user->getId();
        if (!$uid) {
            OA::Json(OA::Guest);
        }
        $yue = OA::$user->getMoney();
        $tixianmoney = (float) $tixianmoney;
        if ($tixianmoney > $yue) {
            OA::Json(1, '提现金额不能大于余额');
        }
        if ($tixianmoney <= 0) {
            OA::Json(1, '提现金额不能等于0');
        }
        if (empty($xingming)) {
            OA::Json(1, '姓名必须输入');
        }
        if (empty($zhifubao)) {
            OA::Json(1, '提现账户必须输入');
        }
        $out_trade_no = self::GenTixianNo();
        $new = new self;
        $new->uid = $uid;
        $new->time = time();
        $new->money = $tixianmoney;
        $new->type = self::type_tixian;
        $new->out_trade_no = $out_trade_no;
        $new->out_trade_no_play = '';
        $new->status = self::status_null;
        $new->ip = Fun::Ip();
        $new->ua = Fun::UA();
        $new->notes = '';
        $new->msg = '';
        $new->admin = 0;
        $new->examine_time = 0;
        $new->play_type = self::PlayType_zhifubao;
        $new->play_time = 0;
        $new->tixian_xingming = $xingming;
        $new->tixian_zhanghu = $zhifubao;
        if ($new->save()) {
            return $out_trade_no;
        } else {
            OA::Json(1, '系统错误,请稍候');
        }

        ///   var_dump($tixianmoney,$xingming,$zhifubao,$yue);exit;
    }

    /**
     * 转账  从$A账户转账到$B账户
     * $B减去钱数,$B累加钱数
     * 并添加记录
     * 必须用事务调用
     */
    public static function zhuanzhangAtoB($A, $B, $money,$notes='') {
        // $Amodel = \App\Models\User\UserModel::where('id', $A)->first();
        $decrCount = UserModel::where('id', $A)->where('money', '>=', $money)->decrement('money', $money);
        if ($decrCount !== 1) {
            if($A==self::system_uid){
                throw new \Exception($A.'系统错误,请和管理员联系');
            }
            throw new \Exception("用户名:".\App\Models\User\UserModel::idToName($A).'余额不足,请先充值');
        }
        $incrCount = UserModel::where('id', $B)->increment('money', $money);
        if ($incrCount !== 1) {
            throw new \Exception('转入错误,请稍候再试');
        } 
        $newdecr = new self;///为用户添加转出记录
        $newdecr->uid = $A;
        $newdecr->time = time();
        $newdecr->money = $money;
        $newdecr->type = self::type_zhuanchu;
        $newdecr->out_trade_no = self::GensystemNo();
        $newdecr->out_trade_no_play = '';
        $newdecr->status = self::status_Success;
        $newdecr->ip = Fun::Ip();
        $newdecr->ua = Fun::UA();
        $newdecr->notes = $notes;
        $newdecr->msg = '';
        $newdecr->admin = 0;
        $newdecr->examine_time = 0;
        $newdecr->play_type = self::PlayType_system;
        $newdecr->play_time = time();
        $newdecr->tixian_xingming = '系统转账';
        $newdecr->tixian_zhanghu =  '系统转账';
        $newdecr->zhuanzhang_uid = $B;
        if (!$newdecr->save()) {
            throw new \Exception('记账错误');
        } 
        $newincr = new self;///为用户添加转入记录
        $newincr->uid = $B;
        $newincr->time = time();
        $newincr->money = $money;
        $newincr->type = self::type_zhuanru;
        $newincr->out_trade_no = self::GensystemNo();
        $newincr->out_trade_no_play = '';
        $newincr->status = self::status_Success;
        $newincr->ip = Fun::Ip();
        $newincr->ua = Fun::UA();
        $newincr->notes = $notes;
        $newincr->msg = '';
        $newincr->admin = 0;
        $newincr->examine_time = 0;
        $newincr->play_type = self::PlayType_system;
        $newincr->play_time = time();
        $newincr->tixian_xingming = '系统转账';
        $newincr->tixian_zhanghu =  '系统转账';
        $newincr->zhuanzhang_uid = $A;
        if (!$newincr->save()) {
            throw new \Exception('记账错误');
        }
        return $newdecr->out_trade_no;
    }

}
